# -*- coding: utf-8 -*-

from django.db import models
import ast
'''
    add some useful Field for Django(v1.11)
    参考: https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/
'''


class ListField(models.TextField):
    """
    List Field
    """
    description = "Stores a python list"

    def __init__(self, *args, **kwargs):
        super(ListField, self).__init__(*args, **kwargs)

    def from_db_value(self, value, expression, connection, context):
        if not value:
            value = []
        try:
            return ast.literal_eval(value)
        except:
            return value

    def to_python(self, value):
        if not value:
            value = []

        if isinstance(value, list):
            return value

        return ast.literal_eval(value)

    def get_prep_value(self, value):
        if value is None:
            return value

        return str(value)

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)


class JSONField(models.TextField):
    """
    JSON Field
    """
    description = "Stores a python dict"

    def __init__(self, *args, **kwargs):
        super(JSONField, self).__init__(*args, **kwargs)

    def from_db_value(self, value, expression, connection, context):
        if not value:
            value = {}
        try:
            return ast.literal_eval(value)
        except:
            return value

    def to_python(self, value):
        if not value:
            value = {}

        if isinstance(value, dict):
            return value

        return ast.literal_eval(value)

    def get_prep_value(self, value):
        if value is None:
            return value

        return str(value)

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)
